package a08_回溯算法;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * a13_子集2复习2
 * </p>
 *
 * @author flyduck
 * @since 2025/2/24
 */
public class a13_子集2复习2 {

    public static void main(String[] args) {
        a13_子集2复习2 test = new a13_子集2复习2();
        System.out.println(test.subsetsWithDup(new int[]{4,4,4,1,4}));
    }

    public List<List<Integer>> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> result = new ArrayList<>();
        LinkedList<Integer> path = new LinkedList<>();
        boolean[] used = new boolean[nums.length];
        traversal(result, path, nums, used,0);
        return result;
    }

    private void traversal(List<List<Integer>> result,
                           LinkedList<Integer> path,
                           int[] nums,
                           boolean[] used,
                           int startIdx){
        result.add(new ArrayList<>(path));

        for (int i = startIdx; i < nums.length; i++) {
            if(i > 0 && nums[i] == nums[i-1] && !used[i-1]){
                continue;
            }
            path.add(nums[i]);
            used[i] = true;
            traversal(result, path, nums, used,i+1);
            path.removeLast();
            used[i] = false;
        }
    }
}
